package cn.wubo.multi.thread.demo01;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * CompletableFuture
 * jdk1.8
 */
public class Demo0107 {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newWorkStealingPool();

        List<CompletableFuture<String>> list = IntStream
                .range(0, 15)
                .mapToObj(i -> (int) (Math.random() * 100))
                .map(l -> CompletableFuture.supplyAsync(() -> {
                            //等待一会
                            try {
                                Thread.sleep(l);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(Thread.currentThread().getName());
                            return l;
                        }, threadPool)
                        .thenApply(Object::toString))
                .collect(Collectors.toList());
        while (list.stream().filter(e -> !e.isDone()).findAny().isPresent()) {
            Thread.sleep(100);
        }


        list.forEach(cf -> {
            try {
                System.out.println(cf.get());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
